using MediatR;
using UniversalAdmin.Application.Common;
using UniversalAdmin.Application.DTOs;
using UniversalAdmin.Domain.Interfaces;

namespace UniversalAdmin.Application.Features.Roles.Queries.GetPagedRoles;

public class GetPagedRolesQueryHandler : IRequestHandler<GetPagedRolesQuery, ApiResult<PagedResult<RoleDto>>>
{
  private readonly IUnitOfWork _uow;

  public GetPagedRolesQueryHandler(IUnitOfWork uow) => _uow = uow;

  public async Task<ApiResult<PagedResult<RoleDto>>> Handle(GetPagedRolesQuery request, CancellationToken ct)
  {
    // 👇 直接调用领域层定义的分页方法
    var (items, total) = await _uow.RoleRepository.GetPagedRolesAsync(
        request.Keyword,
        request.IsActive,
        request.PageIndex,
        request.PageSize);

    // 把领域实体列表转成 DTO
    var dtoList = items.Select(r => new RoleDto
    {
      Id = r.Id,
      Name = r.Name,
      Description = r.Description,
      IsActive = r.IsActive,
      CreatedAt = r.CreatedAt,
      UpdatedAt = r.UpdatedAt,
      UserCount = r.UserRoles.Count,
      Menus = r.RoleMenus.Select(rm => new MenuDto
      {
        Id = rm.Menu!.Id,
        Name = rm.Menu.Name,
        Path = rm.Menu.Path
      }).ToList()
    }).ToList();

    return ApiResult<PagedResult<RoleDto>>.Success(new PagedResult<RoleDto>
    {
      Items = dtoList,
      TotalCount = total,
      PageIndex = request.PageIndex,
      PageSize = request.PageSize
    });
  }
}